﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EasyClassUI.WebRequest;
using EasyClassUI.entity;

namespace EasyClassUI.forms.blog
{
    public partial class blogUC : UserControl
    {
        public static blogUC blogView;
        public blogUC()
        {
            InitializeComponent();
            initializeCell();
        }

        private void DisplayGroupPost(StudyGroup group) {
            int skip = 4;
            List<Post> postsToDisplay = group.Posts.Skip(0).Take(skip).ToList();
            if (postsToDisplay.Count == 0) {
                return;
            }
            while (postsToDisplay.Count < 4) {
                postsToDisplay.Add(new Post() { Title = "" });
            }
            groupBlogDisplayCell displayCell = new groupBlogDisplayCell(group.StudyGroupName, postsToDisplay[0].Title, postsToDisplay[1].Title, postsToDisplay[2].Title, postsToDisplay[3].Title, group);
            allGroupNamesPanel.Controls.Add(displayCell);
        }

        public void initializeCell(List<StudyGroup> groupsToDisplay = null) {
            // 初始化所有帖子列表 一开始就显示所有组的帖子
            allGroupNamesPanel.Controls.Clear();
            if (groupsToDisplay == null) {
                GroupService groupService = new GroupService();
                QueryGroupStatus groups = groupService.QueryWhichGroupHasBeenJoin(User.CurrentUser.Token);
                StudyGroup.GroupIJoined = groups.Groups;
                groupsToDisplay = StudyGroup.GroupIJoined.ToList();
            }

            foreach (StudyGroup group in groupsToDisplay) {
                DisplayGroupPost(group);
            }
        }

        private void newBlogButton_Click(object sender, EventArgs e)
        {
            WriteBlog writeBlog = new WriteBlog();
            writeBlog.Show();
        }

        private void SearchButton_Click(object sender, EventArgs e) {
            List<StudyGroup> result = StudyGroup.GroupIJoined.Where(g => g.StudyGroupName.ToLower().Contains(GroupSearchText.Text.ToLower())).ToList();
            initializeCell(result);
        }

        private void myPostButton_Click(object sender, EventArgs e) {
            allRequiredBlogsForm blogsForm = new allRequiredBlogsForm();
            blogsForm.Show();
        }
    }
}
